package com.jx.gocomtask.webservice.service.impl;

import com.alibaba.druid.wall.violation.ErrorCode;
import com.jx.gocomtask.webservice.DTO.*;
import com.jx.gocomtask.webservice.DTO.query.Query;
import com.jx.gocomtask.webservice.entity.ExtTaskMessage;
import com.jx.gocomtask.webservice.entity.ExtTaskUser;
import com.jx.gocomtask.webservice.entity.ExtTaskUserHistory;
import com.jx.gocomtask.webservice.repository.ExtTaskExtensionRepository;
import com.jx.gocomtask.webservice.repository.ExtTaskMessageRepository;
import com.jx.gocomtask.webservice.repository.ExtTaskUserRepository;
import com.jx.gocomtask.webservice.service.ExtTaskUserService;
import com.jx.gocomtask.webservice.service.GroupService;
import com.jx.gocomtask.webservice.service.SendMessageService;
import com.jx.gocomtask.webservice.service.SystemSuperApp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import phoenics.common.BaseData.BaseErrorCode;
import phoenics.common.exception.NotFoundException;
import phoenics.common.exception.ParamsException;

import javax.annotation.Resource;
import javax.persistence.criteria.*;
import javax.transaction.Transactional;
import java.rmi.ServerException;
import java.sql.Timestamp;
import java.util.*;

/**
 * Created by LWD on 2017/8/8.
 */
@Service
public class ExtTaskServiceImpl implements ExtTaskUserService {
    @Resource
    ExtTaskUserRepository extTaskUserRepository;
    @Resource
    ExtTaskMessageRepository extTaskMessageRepository;
    @Resource
    GroupService groupService;


    @Resource(name="apiurl")
    String gocomeApiUrl;
    @Resource(name="serviceUrl")
    String serviceUrl;
    @Resource(name="serviceIosUrl")
    String serviceIosUrl;
    @Resource(name="serviceAndroidUrl")
    String serviceAndroidUrl;
    @Resource(name="defaultAppId")
    String defaultAppId;
    @Resource(name="defaultGroupAppId")
    private final String method_single="message/single/send/status?";
    @Resource
    SendMessageService sendMessageService;
    @Resource
    ExtTaskExtensionRepository extTaskExtensionRepository;

    @Override
    public Page<ExtTaskUser> findByList(Query query, Pageable pageable) {
        Long messageId = extTaskMessageRepository.findUUID(query.TaskUUId);
        Specification<ExtTaskUser> spec = new Specification<ExtTaskUser>() {
            @Override
            public Predicate toPredicate(Root<ExtTaskUser> root,
                                         CriteriaQuery<?> query, CriteriaBuilder cb) {
                /*
                查询条件拼接
                 */
                List<Predicate> list = new LinkedList<>();
                list.add(cb.equal(root.get("extTaskMessage"), messageId));

                Predicate[] predicates = new Predicate[list.size()];
                predicates = list.toArray(predicates);
                return cb.and(predicates);
            }
        };
        Page<ExtTaskUser> page = extTaskUserRepository.findAll(spec, pageable);
        return page;
    }



    @Override
    @Transactional
    public void updateByUUIDAndTaskUser(String uuid, String taskUser, TaskBody taskBody) {
        ExtTaskMessage extTaskMessage = extTaskMessageRepository.findByUuid(uuid);
        if(null == extTaskMessage || null == extTaskMessage.getExtTaskUser() ||
                extTaskMessage.getExtTaskUser().size() == 0)
            throw new NotFoundException();
        if(extTaskMessage.getStatus().equals(TaskStatus.OVER) ||
                extTaskMessage.getStatus().equals(TaskStatus.FINISHED)  ||
                extTaskMessage.getStatus().equals(TaskStatus.REFUSE)  ||
                extTaskMessage.getStatus().equals(TaskStatus.DELETE) )
            throw new ParamsException(BaseErrorCode.SERVER_ERROR, extTaskMessage.getStatus().getDescTittle().replace("提醒", ""));
        //extTaskMessage.getWorkMode()==WorkStatus .TEAM
       // extTaskMessage.getWorkMode()==WorkStatus.TOGETHER
        ExtTaskUser extTaskUser = null;
        boolean one=false;
        boolean some=false;
        int flag=0;
        for(ExtTaskUser extTaskUser1 : extTaskMessage.getExtTaskUser()){
            if(taskUser.equals(extTaskUser1.getTaskUser())){
                extTaskUser = extTaskUser1;
                extTaskUser.setStatus(taskBody.getStatus());
            }
            if(extTaskUser1.getStatus()==TaskStatus.FINISHED){
            	one=true;
            	flag++;
            }
        }
        if(flag==extTaskMessage.getExtTaskUser().size()){
        	some=true;
        }
        if(null == extTaskUser)
            throw new NotFoundException();
       // extTaskUser.setStatus(taskBody.getStatus());
//        保存历史
        ExtTaskUserHistory history = new ExtTaskUserHistory();
        history.setExtTaskUser(extTaskUser);
        history.setStatus(taskBody.getStatus());
        history.setCreateTime(new Timestamp(System.currentTimeMillis()));
        List<ExtTaskUserHistory> histories = new LinkedList<>();
        histories.add(history);
        extTaskUser.setExtTaskUserHistories(histories);
        List<String> num = new LinkedList<>();
        try {
            extTaskUserRepository.save(extTaskUser);
            num.add("person");
            if((extTaskMessage.getWorkMode()==WorkStatus.TEAM && some)
        			||(extTaskMessage.getWorkMode()==WorkStatus.TOGETHER && one)){
        		 extTaskMessageRepository.updateById(extTaskMessage.getId(), TaskStatus.FINISHED.ordinal());
        	}else if(!extTaskMessage.getStatus().equals(TaskStatus.RECEIVED)){
                extTaskMessage.setStatus(TaskStatus.RECEIVED);
                num.add("create");
               // extTaskMessageRepository.updateById(extTaskMessage.getId(), TaskStatus.RECEIVED.ordinal());
                extTaskMessageRepository.updateById(extTaskMessage.getId(), TaskStatus.RECEIVED.ordinal());
            }
        }catch (Exception e){
            throw new ParamsException(BaseErrorCode.SERVER_ERROR, BaseErrorCode.SERVER_ERROR_MSG);
        }

        for(String action : num) {
            extTaskMessage.setIos(serviceIosUrl + "&taskId=" + uuid);
            extTaskMessage.setUrl(serviceUrl + "&taskId=" + uuid);
            extTaskMessage.setAndroid(serviceAndroidUrl + "&taskId=" + uuid);

            List<ExtTaskUser> userList = new LinkedList<>();
            userList.add(extTaskUser);
            extTaskMessage.setExtTaskUser(userList);
            StatusMessage statusMessage = sendMessageService.updateStatusMessage(extTaskMessage, action, extTaskUser.getTaskUserName());

            sendMessageService.sendMessage(sendMessageService.sendUrl(gocomeApiUrl, defaultAppId, method_single), statusMessage);
        }

//            调用存储过程状态统计
//        extTaskExtensionRepository.updateNumber(extTaskMessage.getId());
    }


}
